package com.enation.app.javashop.api.client;

import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.model.goodssearch.enums.GoodsWordsType;
import com.enation.app.javashop.service.goodssearch.GoodsWordsManager;
import com.enation.app.javashop.service.goodssearch.util.PinYinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fk
 * @version v2.0
 * @Description: ${todo}
 * @date 2018/8/2111:20
 * @since v7.0.0
 */
@RestController
@RequestMapping("/client/goods-words")
@ApiIgnore
public class GoodsWordsClientController {

    @Autowired
    @Qualifier("goodsDaoSupport")
    private DaoSupport daoSupport;

    @Autowired
    private GoodsWordsManager goodsWordsManager;

    @PostMapping("/del")
    public void delete(@RequestParam("words") String words){
        this.daoSupport.execute("update es_goods_words set goods_num  = (case goods_num-1<0 when true  then 0 else goods_num-1 end ) where words=?", words);
    }

    @PostMapping
    public void add(@RequestBody Object o){
        Map map = (Map)o;
        //删除分词表
        String sql = "delete from es_goods_words where words = ?";
        this.daoSupport.execute(sql,map.get("words"));
        this.daoSupport.insert("es_goods_words", map);
    }

    @PostMapping("/add")
    public void addWords(@RequestParam("words") String words){
        String sql = "select * from es_goods_words where words=?";
        List list = this.daoSupport.queryForList(sql, words);
        if (list == null || list.size() == 0) {
            Map map = new HashMap(16);
            map.put("words", words);
            map.put("quanpin", PinYinUtil.getPingYin(words));
            map.put("szm", PinYinUtil.getPinYinHeadChar(words));
            map.put("goods_num", 1);
            map.put("type", GoodsWordsType.SYSTEM.name());
            map.put("sort", 0);
            this.daoSupport.insert("es_goods_words", map);
        } else {
            this.daoSupport.execute("update es_goods_words set goods_num=goods_num+1 where words=?", words);
        }

    }

    @GetMapping("/del/{id}")
    public void delete(@RequestParam("goods_words_type") GoodsWordsType goodsWordsType, @PathVariable("id") Long id){
        goodsWordsManager.delete(goodsWordsType,id);
    }

    @RequestMapping(value = "/update-goods-num", method = RequestMethod.POST)
    public void updateGoodsNum(@RequestParam("words")String words){
        goodsWordsManager.updateGoodsNum(words);
    }

    /**
     * 变更所有平台提示词商品数量
     */
    @RequestMapping(value = "/batch-update-goods-num", method = RequestMethod.POST)
    public void batchUpdateGoodsNum(){
        goodsWordsManager.batchUpdateGoodsNum();
    }

}
